package com.woniu.woniu_bx.controller;

import com.woniu.woniu_bx.exception.OrderStateException;
import com.woniu.woniu_bx.exception.TooPoorException;
import com.woniu.woniu_bx.pojo.*;
import com.woniu.woniu_bx.service.GoodsCategoryService;
import com.woniu.woniu_bx.service.GoodsService;
import com.woniu.woniu_bx.service.OrderService;
import com.woniu.woniu_bx.vo.OrderDetailsVo;
import com.woniu.woniu_bx.vo.OrderVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * 订单控制器
 *
 * @author sjy
 * @create 2022-08-29 11:03
 */
@RestController
@Slf4j
@Validated
@CrossOrigin
public class OrderController {
    @Autowired
    private OrderService orderService;

    @Autowired
    private GoodsCategoryService goodsCategoryService;

    @Autowired
    private GoodsService goodsService;

    /**
     * 多条件分页查询
     *
     * @param orderVo
     * @return
     */
    @RequestMapping("/admin/order/list")
    @PreAuthorize("hasAnyAuthority('order:list')")
    public ResponseEntity<PageBean<Order>> getByPage(@RequestBody @Validated OrderVo orderVo) {
        PageBean<Order> pageBean = new PageBean<>();
        pageBean = orderService.getByPage(orderVo, 10);
        return ResponseEntity.SUCCESS("订单查询成功", pageBean);
    }

    /**
     * 订单导出
     *
     * @param response
     * @return
     * @throws IOException
     */
    @PostMapping("/admin/order/exportFile")
    @PreAuthorize("hasAnyAuthority('order:list')")
    public void export(HttpServletResponse response) throws IOException {
        List<Order> orders = orderService.getAll();
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("订单表");
        int lastRowNum = 0;
        Row titleRow = sheet.createRow(lastRowNum);
        String[] titles = {"订单编号", "下单时间", "用户账号", "商品数量", "订单价格", "商品编号", "陪玩操作", "订单状态"};
        //写入列名
        for (int i = 0; i < titles.length; i++) {
            //创建列
            Cell titleCell = titleRow.createCell(i);
            //设置单元格属性
            titleCell.setCellType(CellType.STRING);
            //写入内容
            titleCell.setCellValue(titles[i]);
        }
        lastRowNum++;
        for (int i = 0; i < orders.size(); i++) {
            Row contentRow = sheet.createRow(lastRowNum + i);
            Order order = orders.get(i);

            String pwOption = null;
            if (order.getPwOption().equalsIgnoreCase("y")) {
                pwOption = "接受订单";
            } else if (order.getPwOption().equalsIgnoreCase("n")) {
                pwOption = "拒绝订单";
            } else if (order.getPwOption().equalsIgnoreCase("o")) {
                pwOption = "处理超时";
            } else {
                pwOption = "等待处理";
            }
            String status = null;
            if (order.getState().equalsIgnoreCase("1")) {
                status = "待确认";
            } else if (order.getState().equalsIgnoreCase("2")) {
                status = "进行中";
            } else if (order.getState().equalsIgnoreCase("3")) {
                status = "已服务";
            } else if (order.getState().equalsIgnoreCase("4")) {
                status = "已取消";
            } else if (order.getState().equalsIgnoreCase("5")) {
                status = "已完成";
            } else {
                status = "已删除";
            }
            String[] contents = {order.getOrderNum(), order.getBuyTime(), order.getUser().getAccount(), order.getNum().toString(), order.getMoney().toString(), order.getGoodsId().toString(), pwOption, status};
            for (int j = 0; j < contents.length; j++) {
                Cell cell = contentRow.createCell(j);
                cell.setCellType(CellType.STRING);
                cell.setCellValue(contents[j]);
            }
        }
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-disposition", "attachment;filename=" + "订单表.xlsx");
        response.flushBuffer();
        OutputStream outputStream = response.getOutputStream();
        workbook.write(response.getOutputStream());
        workbook.close();
        outputStream.flush();
        outputStream.close();
    }

    /**
     * 展示各类别的订单数量
     *
     * @return
     */
    @RequestMapping("/admin/order/countOrder")
    public ResponseEntity<List<Order>> getOrderNumberGroupByCategoryId() {
        List<Order> orders = orderService.getOrderNumberGroupByCategoryId();
        List<Order> newOrders = new ArrayList<>();
        for (Order order : orders) {
            GoodsCategory goodsCategory = goodsCategoryService.getById(order.getCategoryId());
            order.setCategoryName(goodsCategory.getName());
            newOrders.add(order);
        }
        return ResponseEntity.SUCCESS("查询成功", newOrders);
    }

    /**
     * 后台：根据订单id查询订单详情
     *
     * @param id
     * @return
     */
    @GetMapping("/order/details/{id}")
    @PreAuthorize("hasAnyAuthority('order:list')")
    public ResponseEntity<OrderDetailsVo> getByGoodsId(@Min(value = 1, message = "id不能小于1") @PathVariable int id) {
        Order order = orderService.getOrderById(id);
        Goods goods = goodsService.getCategoryNameByid(order.getGoodsId());
        OrderDetailsVo orderDetailsVo = new OrderDetailsVo();
        orderDetailsVo.setOrder(order);
        orderDetailsVo.setGoods(goods);
        return ResponseEntity.SUCCESS("查询成功", orderDetailsVo);
    }

    /**
     * 前台：根据订单id查询订单详情
     *
     * @param id
     * @return
     */
    @GetMapping("/order/detail/{id}")
    public ResponseEntity getOrderDetailById(@Min(value = 1, message = "id不能小于1")@NotNull @PathVariable Integer id) {
        return ResponseEntity.SUCCESS("查询订单详情成功", orderService.getOrderDetailById(id));
    }


    /**
     * 根据用户id查询订单列表
     * 前台专用
     *
     * @param userId
     * @return
     */
    @RequestMapping("/order/list/{userId}")
    public ResponseEntity<List<Order>> getByUserId(@Min(value = 1, message = "用户id不能小于1") @PathVariable int userId) {
        List<Order> orders = orderService.getByUserId(userId);
        return ResponseEntity.SUCCESS("查询成功", orders);
    }

    /**
     * 删除订单
     * 前台专用
     *
     * @param id
     * @return
     */
    @RequestMapping("/order/delete/{id}")
    public ResponseEntity delete(@Min(value = 1, message = "id不能小于1") @PathVariable int id) {
        orderService.delete(id);
        return ResponseEntity.SUCCESS("删除成功", null);
    }

    /**
     * 批量删除订单
     * 前台专用
     *
     * @param ids
     * @return
     */
    @RequestMapping("/order/deleteSome")
    public ResponseEntity deleteSome(int[] ids) {
        for (int id : ids) {
            orderService.delete(id);
        }
        return ResponseEntity.SUCCESS("删除成功", null);
    }

    /**
     * 买家确认收货
     * 前台专用
     *
     * @param id
     * @return
     */
    @RequestMapping("/order/confirm/{id}")
    public ResponseEntity confirm(@Min(value = 1, message = "id不能小于1") @PathVariable int id) {
        Order order = orderService.getOrderById(id);
        if (!order.getState().equalsIgnoreCase("3")) {
            throw new OrderStateException("服务未完成，不能确认收货");
        }
        orderService.confirm(id);
        return ResponseEntity.SUCCESS("收货成功", null);
    }

    /**
     * 卖家确认服务已完成
     * 前台专用
     *
     * @param id
     * @return
     */
    @RequestMapping("/order/served/{id}")
    public ResponseEntity served(@Min(value = 1, message = "id不能小于1") @PathVariable int id) {
        Order order = orderService.getOrderById(id);
        if (!order.getState().equalsIgnoreCase("2")) {
            throw new OrderStateException("你暂未接受此订单，不能进行服务");
        }
        orderService.served(id);
        return ResponseEntity.SUCCESS("服务已完成", null);
    }

    /**
     * 下订单
     *
     * @param order
     * @return
     */
    @RequestMapping("/order/add")
    public ResponseEntity add(@RequestBody Order order) {
        try {
            orderService.add(order);
        } catch (TooPoorException e) {
            return ResponseEntity.NO_MONEY("余额不足", null);
        }
        return ResponseEntity.SUCCESS("已下单", null);
    }

    /**
     * @return com.woniu.woniu_bx.pojo.ResponseEntity
     * @Description 根据陪玩id查出其对应订单状态或所有状态的所有订单
     * @Date 16:17 2022/9/2
     * @Author 魏才林
     * @Param [id]
     **/
    @PostMapping("/order/accept/{id}")
    public ResponseEntity accept(@Min(value = 1, message = "id不能小于1") @PathVariable Integer id) {
        Order order = orderService.getOrderById(id);
        if (!order.getState().equalsIgnoreCase("1")) {
            throw new OrderStateException("订单并未处于待确认状态，接受新订单失败！");
        }
        orderService.accept(id);
        return ResponseEntity.SUCCESS("接受新订单服务已完成", null);
    }

    /**
     * @return com.woniu.woniu_bx.pojo.ResponseEntity
     * @Description 根据陪玩id查出其对应订单状态或所有状态的所有订单
     * @Date 16:17 2022/9/2
     * @Author 魏才林
     * @Param [id]
     **/
    @PostMapping("/order/refuse/{id}")
    public ResponseEntity refuse(@Min(value = 1, message = "id不能小于1") @PathVariable Integer id) {
        Order order = orderService.getOrderById(id);
        if (!order.getState().equalsIgnoreCase("1")) {
            throw new OrderStateException("订单并未处于待确认状态，拒绝新订单失败！");
        }
        orderService.refuse(id);
        return ResponseEntity.SUCCESS("拒绝新订单已完成", null);
    }

    /**
     * @return com.woniu.woniu_bx.pojo.ResponseEntity
     * @Description 根据陪玩id查出其对应订单状态或所有状态的所有订单
     * @Date 13:17 2022/9/2
     * @Author 魏才林
     * @Param [orderVo]
     **/
    @PostMapping("/order/getPwOrder")
    public ResponseEntity getPwOrder(@RequestBody OrderVo orderVo) {
        Integer pageSize = 7;
        return ResponseEntity.SUCCESS("获取陪玩订单", orderService.getOrdersByPwIdAndStatus(orderVo, pageSize));
    }

    /**
     * @return com.woniu.woniu_bx.pojo.ResponseEntity
     * @Description 根据普通用户id查出其对应订单状态或所有状态的所有订单
     * @Date 15:17 2022/9/2
     * @Author 魏才林
     * @Param [orderVo]
     **/
    @PostMapping("/order/getUserOrder")
    public ResponseEntity getUserOrder(@RequestBody OrderVo orderVo) {
        Integer pageSize = 7;
        return ResponseEntity.SUCCESS("获取陪玩订单", orderService.getOrdersByUserIdAndStatus(orderVo, pageSize));
    }
}
